<?php
namespace app\api\controller\company;

use app\api\controller\Baseuser;
use app\common\model\company\Company as Companymodel;
use app\common\model\company\CompanyFile as CompanyFileModel;
use app\common\model\user\User as UserModel;
use app\common\model\company\Company;
use app\common\model\company\CompanyFileType;
use app\common\model\customer\Subscribe;
use think\facade\Env;
use app\common\model\power\Rolepower;
use think\File;

class Companyfile extends Baseuser
{
    /**
     * 产生jwt加密串，参考session
     */
    public function initialize()
    {
        parent::initialize();
        // self::is_login();
        // Rolepower::powerguard(201102);
    }

    /**
     * 获取产废单位排查清单列表
     * @return [type] [description]
     */
    public function getcompanyinfo(){
        $id = input('id');
        if(empty($id)){
            return myerr('缺少参数');
        }
        if($id=='-1'){
            $company['Name'] = '【本企业】';
            if (Rolepower::ispower(206002)) {
                //管理员权限
            }else{
                return moerr('权限不足，无法查看客户文件信息','','goback');
            }
        }else{
            $company = Company::get($id);
            if(empty($company)){
                return myerr('没找到您需要的企业','','goback');
            }
            if (Rolepower::ispower(204015)) {
                //管理员权限
            } else if (Rolepower::ispower(201007)) {
                if(get_config_value('company_file_only_show')){
                    //若不需要验证直接通过
                }else if($company->BussinessId == Pub::userid()){
                    //客户负责人 通过验证
                }else{
                    return moerr('权限不足，无法查看客户文件信息','','goback');
                }
            } else if(Rolepower::ispower(101007)) {
               //判断是否为客户
                $mycompany = Company::where('UserId',$this->user_id)->find();
                if(!empty($mycompany) && $company['CompanyId']==$mycompany['CompanyId']){
                    //企业负责人通过验证
                }else{
                    return moerr('权限不足，无法查看客户文件信息','','goback');
                }
            }
        }
        $list = CompanyFileModel::where('CompanyId',$id)->order('CreateTime desc')->with('typeinfo')->select();
        $file = [];
        foreach ($list as $key => $value) {
            $file[$value['TypeId']][] = $value;
        }
        $file2 = [];
        foreach ($file as $key => $value) {
            $file2[] = ['Name'=>$value[0]['typeinfo']['Name'],'List'=>$value];
        }
        $rdata = ['CompanyName'=>$company['Name'],'List'=>$file2];
        return myok($rdata); 
    }

    /**
     * 获取创建前的数据
     * @return [type] [description]
     */
    public function getcreateinitinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('请选择企业','','goback');
        }
        if($id==-1){
            $company['Name'] =  '【本企业】';
        }else{
            $company = Company::get($id);
            if(empty($company)){
                return myerr('没找到您需要的企业','','goback');
            }   
        }
        $user = UserModel::get($this->user_id);
        $data['company'] = ['Name'=>$company['Name']];
        $data['filetypelist']    =CompanyFileType::where('State',CompanyFileType::STATEOK)->select();
        return myok($data);
    }

    /**
     * 获取数据
     * @return [type] [description]
     */
    public function getinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数','','goback');
        }
        $data = CompanyFilemodel::user_getinfo($id);
        $data['filetypelist']    =CompanyFileType::where('State',CompanyFileType::STATEOK)->select();
        return myok($data);
    }

    /**
     * 删除此摸排单
     * @return [type] [description]
     */
    public function deleteinfo(){
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数','','goback');
        }
        $data = CompanyTouchmodel::deleteinfo($id);
        return myok($data);
    }

    /**
     * 修改摸排单
     * @return [type] [description]
     */
    public function reinfo()
    {
        $idata = input('post.');
        if (empty($idata)) {
            return myerr('缺少需要的信息');
        }
        if (empty($idata['id'])) {
            return myerr('没找到您需要修改的信息');
        }
        $company = Company::get($idata['CompanyId']);
        if (Rolepower::ispower(204015)) {
            //管理员权限
        } else if (Rolepower::ispower(201007)) {
            if(get_config_value('company_file_only_show')){
                //若不需要验证直接通过
            }else if($company->BussinessId == Pub::userid()){
                //客户负责人 通过验证
            }else{
                return moerr('权限不足，无法查看客户文件信息','','goback');
            }
        }

        $ndata['FileId'] = $idata['id'];
        $filed              = ['Img', 'Name', 'Note', 'TypeId', 'SubscribeTime'];
        foreach ($filed as $key => $value) {
            if (isset($idata[$value])) {
                $ndata[$value] = trim($idata[$value]);
            }
        }
        //添加排查清单
        $customerid = CompanyFileModel::user_re($ndata);
        //删除预约
        Subscribe::where('CompanyFileId',$customerid)->delete();
        //添加预约
        if(!empty($idata['SubscribeTime'])){
            $nidata['SubscribeTime'] = $idata['SubscribeTime'];
            $nidata['CompanyId'] = $idata['CompanyId'];
            $nidata['CompanyFileId'] = $customerid;
            $nidata['Content'] = $idata['SubscribeNote'];
            $nidata['u_id'] = $this->user_id;
            $subscribe = new Subscribe;
            $subscribe->addSubscribe($nidata);
        }
        return myok($customerid);
    }


    /**
     * 新增摸排信息
     * @return [type] [description]
     */
    public function createinfo()
    {
        $idata = input('post.');
        if (empty($idata)) {
            return myerr('缺少需要的信息');
        }
        if (empty($idata['id'])) {
            return myerr('请选择企业');
        }
        if (empty($idata['TypeId'])) {
            return myerr('请选择文件分类');
        }
        $ndata['CompanyId'] = $idata['id'];
        $filed              = ['Img', 'Name', 'Note', 'TypeId', 'SubscribeTime'];
        foreach ($filed as $key => $value) {
            if (!empty($idata[$value])) {
                $ndata[$value] = trim($idata[$value]);
            }
        }
        //添加文件内容
        $customerid = CompanyFileModel::user_create($ndata);
        //添加预约信息
        if(!empty($idata['SubscribeTime'])){
            $idata['SubscribeTime'] = $idata['SubscribeTime'];
            $idata['CompanyId'] = $idata['id'];
            $idata['CompanyFileId'] = $customerid;
            $idata['Content'] = $idata['SubscribeNote'];
            $idata['u_id'] = $this->user_id;
            $subscribe = new Subscribe;
            $subscribe->addSubscribe($idata);
        }
        return myok($customerid);
    }

    /**
     * 图片上传
     * @return [type] [description]
     */
    public function upimg()
    {
        $type = 'companyfile';
        try {
            $file = request()->file('img');
        } catch (\Exception $e) {
            return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        if (!is_null($file)) {
            try {
                $save_path = Env::get('root_path') . 'public/static' . '/upimg/customer/' . $type . '/';
                $info      = $file->validate(["size" => 50000000, 'ext' => 'jpg,png,gif'])->rule("date")->move($save_path);
                //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
                $image = \think\Image::open($save_path . '/' . $info->getSaveName());
                $image->thumb(2000, 2000)->save($save_path . '/' . $info->getSaveName());
                if ($info) {
//getSaveName();
                    $p = $info->getFilename();
                    return json_encode(['status' => 'ok', 'data' => SERVERURL . 'static/upimg/customer/' . $type . '/' . date('Ymd', time()) . '/' . $p]);
                } else {
                    return json_encode(['status' => 'error', 'data' => $info->getError()]);
                }
            } catch (\Exception $e) {
                return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
            }

        } else {
            return json_encode(['status' => 'error', 'data' => '没有找到需要上传的图片']);
        }
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
